package com.example.server.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.web.domain.*;
import com.example.server.web.domain.Class;
import com.example.server.web.domain.dto.CourseClassTeacherParamDto;
import com.example.server.web.domain.page.PageQueryDto;
import com.example.server.web.domain.vo.CourseClassTeacherVo;
import com.example.server.web.exception.CustomException;
import com.example.server.web.mapper.CourseClassTeacherMapper;
import com.example.server.web.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2023-04-04
 */
@Service
public class CourseClassTeacherServiceImpl extends ServiceImpl<CourseClassTeacherMapper, CourseClassTeacher> implements CourseClassTeacherService {

    @Autowired
    private CourseClassTeacherMapper courseClassTeacherMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private ClassService classService;

    @Autowired
    private StudentService studentService;

    @Override
    public void add(CourseClassTeacher courseClassTeacher) {
        //判断是否存在同一个学年，同一课程，同一班级
        checkExist(courseClassTeacher);
        courseClassTeacher.setStatus(0);
        int insert = courseClassTeacherMapper.insert(courseClassTeacher);
        if (insert < 1) {
            throw new CustomException("新增失败");
        }
    }

    private void checkExist(CourseClassTeacher courseClassTeacher) {
        LambdaQueryWrapper<CourseClassTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseClassTeacher::getCourseId,courseClassTeacher.getCourseId());
        wrapper.eq(CourseClassTeacher::getClassId,courseClassTeacher.getClassId());
        wrapper.eq(CourseClassTeacher::getYear,courseClassTeacher.getYear());
        List<CourseClassTeacher> courseClassTeachers = courseClassTeacherMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(courseClassTeachers)){
            throw new CustomException("该班级已经添加过此课程了");
        }
    }

    @Override
    public Map getPage(CourseClassTeacher courseClassTeacher, PageQueryDto pageQueryDto) {
        //构建条件
        LambdaQueryWrapper<CourseClassTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(courseClassTeacher.getClassId() != null,CourseClassTeacher::getClassId,courseClassTeacher.getClassId());
        wrapper.eq(courseClassTeacher.getTeacherId() != null,CourseClassTeacher::getTeacherId,courseClassTeacher.getTeacherId());
        wrapper.eq(courseClassTeacher.getYear() != null,CourseClassTeacher::getYear,courseClassTeacher.getYear());
        //查询获得关联的分页信息
        Page<CourseClassTeacher> page = this.page(new Page<>(pageQueryDto.getPage(), pageQueryDto.getLimit()), wrapper);
        List<CourseClassTeacher> courseClassTeacherList = page.getRecords();

        List<CourseClassTeacherVo> courseClassTeacherVos = getCourseClassTeacherVos(courseClassTeacherList);

        Map<String, Object> map = new HashMap<>();
        map.put("list",courseClassTeacherVos);
        map.put("total",page.getTotal());
        return map;
    }

    /**
     * 获得课程-班级-教师 视图类
     * @param courseClassTeacherList
     * @return
     */
    private List<CourseClassTeacherVo> getCourseClassTeacherVos(List<CourseClassTeacher> courseClassTeacherList) {
        //新建视图类
        List<CourseClassTeacherVo> courseClassTeacherVos = new ArrayList<>();

        try {
            //复制且查询班级姓名，课程姓名，教师名称
            courseClassTeacherList.forEach(item ->{
                //新建视图类
                CourseClassTeacherVo courseClassTeacherVo = new CourseClassTeacherVo();
                //查询班级名称
                Class aClass = classService.getById(item.getClassId());
                String className = ObjectUtils.isEmpty(aClass) ? null:aClass.getClassName();
                int classPersonNum = ObjectUtils.isEmpty(aClass) ? 0:aClass.getClassPersonNum();
                //查询教师名称
                Teacher teacher = teacherService.getById(item.getTeacherId());
                String teacherName = ObjectUtils.isEmpty(teacher) ? null:sysUserService.getById(teacher.getUserId()).getName();
                //查询课程名字
                Course course = courseService.getById(item.getCourseId());
                String courseName = ObjectUtils.isEmpty(course) ? null:course.getCourseName();
                //复制
                BeanUtils.copyProperties(item,courseClassTeacherVo);
                //再设置值
                courseClassTeacherVo.setCourseName(courseName);
                courseClassTeacherVo.setClassName(className);
                courseClassTeacherVo.setTeacherName(teacherName);
                courseClassTeacherVo.setClassPersonNum(classPersonNum);

                courseClassTeacherVos.add(courseClassTeacherVo);
            });
        } catch (Exception e){
            throw new CustomException("查询失败");
        }
        return courseClassTeacherVos;
    }

    @Override
    public Map getPageByStuId(Long studentId, PageQueryDto pageQueryDto) {
        //查询学生
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        Student student = studentService.getOne(wrapper.eq(Student::getUserId,studentId));
        if(ObjectUtils.isEmpty(student)){
            throw new CustomException("学生信息不存在");
        }

        CourseClassTeacher courseClassTeacher = new CourseClassTeacher();
        courseClassTeacher.setClassId(student.getClassId());
        Map page = getPage(courseClassTeacher, pageQueryDto);
        return page;
    }

    @Override
    public Map getAllToPage(CourseClassTeacherParamDto paramDto, PageQueryDto pageQueryDto) {
        Map<String, Object> map = new HashMap<>();
        Integer page = pageQueryDto.getPage();
        Integer limit = pageQueryDto.getLimit();
        if (page <= 0 || limit < 0){
            throw new CustomException("page必须大于0或者limit必须大于等于0");
        }
        //查询总条数
        Long total = courseClassTeacherMapper.getAllToNum(paramDto);
        //查询全部信息的分页信息
        List<CourseClassTeacherVo> courseClassTeacherVos = courseClassTeacherMapper.getAllToPage(paramDto,(page-1)*limit,limit);
        map.put("list",courseClassTeacherVos);
        map.put("total",total);
        return map;
    }
}
